import json
from openai import OpenAI

# 设置OpenAI API客户端
client = OpenAI(
    base_url="https://api.gptsapi.net/v1",
    api_key="sk-kghaf948e5e3bc901fdb866fa5f1ffe18d19d9961a8N5pAg"
)

# 从文件加载数据
with open('extracted_data.json', 'r', encoding='utf-8') as file:
    legal_documents = json.load(file)

# 定义调用GPT-4 API的函数
def extract_features(text):
    try:
        prompt = (
            "你是一个可以从法律文本中提取关键信息的助手。请按照以下格式处理文本：\n"
            "1. **原告信息**:\n   - 姓名：\n   - 性别：\n   - 出生日期：\n   - 民族：\n   - 职业：\n   - 住址：\n\n"
            "2. **被告信息**:\n  "
            "3. **案件情况**:\n "
            "4. **请求**:\n   - 原告请求：\n\n"
            "5. **家庭关系**:\n   - 关系描述：\n\n"
            "6. **证据支持**:\n   - 证据类型：\n\n"
            "7. **被告答辩情况**:\n   - 答辩情况：\n\n"
            f"以下是法律文本，请按照上述格式提取关键信息：\n\n{text}"
        )
        response = client.chat.completions.create(
            model="gpt-4o",
            messages=[
                {"role": "system", "content": "你是一个可以从法律文本中提取关键信息的助手。"},
                {"role": "user", "content": prompt}
            ]
        )
        print(response)  # 调试输出响应内容
        content = response.choices[0].message.content.strip()  # 确保访问方式正确
        return content
    except Exception as e:
        print(f"Error extracting features: {e}")
        return None

# 批量处理数据并保存结果
extracted_features = []

for document in legal_documents:
    features = extract_features(document)
    if features:
        extracted_features.append(features)
    else:
        extracted_features.append("Error processing document")

# 将结果保存到文件
with open('extracted_features_4o.json', 'w', encoding='utf-8') as file:
    json.dump(extracted_features, file, ensure_ascii=False, indent=4)

print("特征提取完成，结果已保存到 'extracted_features_4o.json' 文件中。")
